import requests

import csv

# 创建文件 utf-8-sig处理乱码
f = open('static/bilibili_data.csv', 'w', encoding='utf-8-sig', newline='')
fieldnames = ['昵称', '地区', '评论']
writer = csv.DictWriter(f, fieldnames=fieldnames)  # ← DictWriter
writer.writeheader()
# url = 'https://www.bilibili.com/video/BV1XAWBzMEew/?spm_id_from=333.1007.tianma.1-1-1.click&vd_source=2bb056523d7d96790a0a8db4a4fb9e75'
url = 'https://api.bilibili.com/x/v2/reply/wbi/main?oid=115383457612323&type=1&mode=2&pagination_str=%7B%22offset%22:%22%22%7D&plat=1&seek_rpid=&web_location=1315875&w_rid=e2dcf5573ad5b9881d03a008dad3bc55&wts=1761961718'


headers = {
    "cookie":"buvid3=364519AA-EB6E-176B-FBE9-9C1D2EE1202A33861infoc; b_nut=1761788433; bsource=search_baidu; _uuid=10E22CB56-6AAD-C3B2-1DC9-6F316B391014535441infoc; enable_web_push=DISABLE; buvid4=2210D469-86D0-8EE1-6EE3-65B01F79F1CF34775-025103009-R3gyyKLdI6CMoUsVGhPMgg%3D%3D; buvid_fp=364a2990e9fb60e7f0e8c19127ad0010; CURRENT_QUALITY=0; rpdid=|(J|YukR~Y~~0J'u~Yu~mYuuJ; b_lsid=515310FFA_19A3D12F192; home_feed_column=5; browser_resolution=1710-957; csrf_state=0b2ed3a9be2ba5f6c21a9bca470fcfdd; SESSDATA=6d59704b%2C1777513443%2Cae7e0%2Ab1; bili_jct=d03ded790f14e933b3abb29b715b36f6; DedeUserID=3546755123644478; DedeUserID__ckMd5=4b63421c3b058f8b; sid=5fob3eh0; theme-tip-show=SHOWED; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjIyMjA2NjksImlhdCI6MTc2MTk2MTQwOSwicGx0IjotMX0.OkOmtRjwxH8TjByJcwx8Cct1SbwAX5d04oo1FtjOnHg; bili_ticket_expires=1762220609; theme-avatar-tip-show=SHOWED; CURRENT_FNVAL=4048",
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
}


response = requests.get(url, headers=headers)
# print(response.status_code)
text = response.text
# print(text)
# print(type(text))

json_data = response.json()
# print(json_data)

replies = json_data['data']['replies']
# print(replies)
for reply in replies:
    # print(reply)
    dit = {
        '昵称': reply['member']['uname'],
        '地区': reply['reply_control']['location'].replace('IP属地：',''),
        '评论': reply['content']['message'],
    }
    # csv_writer.writerow(dit)
    writer.writerow(dit)
    print(dit)